import {computed, ref, Ref, unref} from "vue";
import {Pagination, Sorting, Activity, Filters} from "../types";
import { useRecordStore } from "../store/record";
import { useDrawStore } from "../store/draw";



const makePaginationRef = () => ref<Pagination>({ page: 1, perPage: 10, total: 0 })
const makeSortingRef = () => ref<Sorting>({ sortBy: 'created_at', sortingOrder: 'desc' })
const makeFiltersRef = () => ref<Partial<Filters>>({ activityId: '102', prizeId: '1' })

export const useRecordPage =  (options?: { sorting?: Ref<Sorting>; pagination?: Ref<Pagination>; filters?: Ref<Partial<Filters>> }) => {

  const {sorting = makeSortingRef(), pagination = makePaginationRef(), filters = makeFiltersRef()} = options ?? {}
  const isLoading = ref(false)

  const recordStore  = useRecordStore();
  const drawStore  = useDrawStore();

  const fetch = async () => {
    await recordStore.getPage({
      filters: unref(filters),
      sorting: unref(sorting),
      pagination: unref(pagination),
    })
  }

  fetch()

  const activeDraw = async ()=> {
    await drawStore.draw({filters: unref(filters)})
    await fetch()
  }

  const dataList = computed(() => {
    return recordStore.items as Activity[]
  });

  return {
    fetch,
    activeDraw,
    filters,
    dataList,
    isLoading,
    sorting,
    pagination
  }
}
